<!-- 资产列表 -->
<template>
  <ContainerLayoutV2 ref="containerLayoutRef" class="asset-statistics">
    <template #form>
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <UserInput v-model="queryForm.user" />
        <DeptCascader v-model="queryForm.deptIds" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template #toolbar>
      <el-button plain size="small" type="primary" :icon="Plus" @click="handleClickBtnAdd">新建</el-button>
      <el-divider direction="vertical" />
      <el-button-group class="ml-4">
        <el-button plain size="small" v-for="item in useAssetStatusStore().assetStatus" :type="typeArr[item.dictValue * 1 + 1].type" :icon="typeArr[item.dictValue * 1 + 1].icon" @click="handleClickBtnBatchUpdateStatus(item.dictValue)">批量{{ item.dictLabel }}</el-button>
      </el-button-group>
    </template>
    <template #tables>
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" :span-method="objectSpanMethod" scrollbar-always-on style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column prop="deptName" label="部门" width="120" />
        <el-table-column prop="userNick" label="姓名" width="150" />
        <el-table-column prop="name" label="资产名称" width="150" />
        <el-table-column prop="code" label="编码" width="150" />
        <el-table-column label="资产类型" width="100">
          <template #default="scope">
            <TextTeg :id="scope.row.assetCategory" :datelist="useAssetCategoryStore().assetCategory" />
          </template>
        </el-table-column>
        <el-table-column prop="assetStatus" label="状态" width="90">
          <template #default="scope">
            <TextTeg v-if="false" :id="scope.row.assetStatus" :datelist="useAssetStatusStore().assetStatus" />
            <DropdownStatus v-model="scope.row.assetStatus" @change="(value) => handleChangeStatus(scope.row, value)" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="remark" />
        <el-table-column label="操作" width="130" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleClickBtnEdit(scope.row)" :icon="Edit">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleClickBtnDelete(scope.row)" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </ContainerLayoutV2>
  <DialogAssetStatistics ref="dialogAssetStatisticsRef" @submited="handlerDialogSubmited" />
</template>
<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { useAssetCategoryStore, useAssetStatusStore } from '../stores'
import ContainerLayoutV2 from '../layout/ContainerLayoutV2.vue'
import { Delete, Search, Refresh, Plus, Edit, CloseBold, Select, SemiSelect } from '@element-plus/icons-vue'
import UserInput from '../layout/FormTableLayout/UserInput.vue'
import DeptCascader from '../layout/FormTableLayout/DeptCascader.vue'
import api from '../api'
import DialogAssetStatistics from '../components/dialog/DialogAssetStatistics.vue'
import TextTeg from '../components/TableParts/TextTeg.vue'
import DropdownStatus from '../components/AssetStatistics/DropdownStatus.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import _ from 'lodash'

const dataResult = ref()
const dataResult2 = ref()
const loading = ref(false)
const containerLayoutRef = ref<InstanceType<typeof ContainerLayoutV2> | null>(null)
const dialogAssetStatisticsRef = ref<InstanceType<typeof DialogAssetStatistics> | null>(null)
const selectable = (row: any) => row.status !== 1
const multipleSelection = ref<any[]>([])
const typeArr = [
  { type: 'danger', icon: CloseBold },
  { type: 'warning', icon: SemiSelect },
  { type: 'success', icon: Select },
]
const tableHeight = ref(500)
const tableData = ref<any[]>([])

const queryForm = reactive({
  user: '',
  deptIds: [] as any[] | string[],
})
onMounted(async () => {
  // await init()
  if (containerLayoutRef.value && containerLayoutRef.value.tableContainer) {
    const tableContainer = containerLayoutRef.value.tableContainer
    tableHeight.value = tableContainer.offsetHeight
  }
})

// 资产
const getAssetList = async () => {
  const deptIds: any[] = []
  queryForm.deptIds.forEach((e: any) => {
    deptIds.push(e[e.length - 1])
  })

  loading.value = true
  tableData.value = []
  const params = {
    pageSize: 999999,
  }
  if (queryForm.user) {
    Object.assign(params, { userName: queryForm.user })
  }
  if (deptIds.length > 0) {
    Object.assign(params, { deptIds: deptIds.join(',') })
  }
  const res = await api.Asset.getList(params)

  const groupedData: any = {}
  res.forEach((e: any) => {
    const { deptId, userId } = e
    if (!groupedData[deptId]) {
      groupedData[deptId] = {}
    }
    if (!groupedData[deptId][userId]) {
      groupedData[deptId][userId] = []
    }
    groupedData[deptId][userId].push(e)
  })

  loading.value = false
  tableData.value = Object.values(groupedData)
    .flatMap((dept: any) => Object.values(dept))
    .flat()

  dataResult.value = await countByNameAndIndex(tableData.value, 'deptId')
  dataResult2.value = await countByNameAndIndex(tableData.value, 'userId')
  console.log('dataResult:', dataResult.value)
}
const countByNameAndIndex = (data: any[], field: string) => {
  const nameCountMap: { [key: string]: number } = {}
  const firstIndexMap: { [key: string]: number } = {}
  data.forEach((item: any, index) => {
    if (!nameCountMap[item[field]]) {
      nameCountMap[item[field]] = 1
      firstIndexMap[item[field]] = index
    } else {
      nameCountMap[item[field]]++
    }
  })

  const mergedObject: { [key: string]: Array<number> } = {}
  for (const name in nameCountMap) {
    mergedObject[firstIndexMap[name]] = [nameCountMap[name], 1]
  }
  return mergedObject
}

const objectSpanMethod = ({ rowIndex, columnIndex }: any) => {
  console.log('rowIndex:', rowIndex, columnIndex)

  if (columnIndex == 1) {
    let res = dataResult.value[rowIndex]
    if (res) {
      return {
        rowspan: res[0],
        colspan: res[1],
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }
  if (columnIndex == 2) {
    let res = dataResult2.value[rowIndex]
    if (res) {
      return {
        rowspan: res[0],
        colspan: res[1],
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
  }
}

const init = async () => {
  await getAssetList()
}

const handleClickBtnEdit = async (item: any) => {
  if (dialogAssetStatisticsRef.value) {
    dialogAssetStatisticsRef.value.openDialog(item)
  }
}

const handleClickBtnDelete = async (item: any) => {
  ElMessageBox.confirm('确定删除?', '提示')
    .then(async () => {
      const { code } = await api.Asset.deleteById(item.id)
      if (code !== 200) {
      } else {
        ElMessage({
          message: `删除成功！`,
          grouping: true,
          type: 'success',
        })
      }
      handlerDialogSubmited()
    })
    .catch(() => {})
}
const handleClickBtnSubmit = async () => {
  await init()
}
const handleClickBtnReset = async () => {
  queryForm.user = ''
  queryForm.deptIds = []
  await init()
}

const handleChangeStatus = async (item: any, value: any) => {
  ElMessageBox.confirm(`确定要修改状态吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await api.Asset.update({ id: item.id, assetStatus: value.dictValue })
      if (res.code == 200) {
        ElMessage({
          message: `修改状态成功！`,
          grouping: true,
          type: 'success',
        })
        await handlerDialogSubmited()
      } else {
        ElMessage({
          message: `修改状态失败！`,
          grouping: true,
          type: 'error',
        })
      }
    })
    .catch(() => {})
}
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
const handleClickBtnBatchUpdateStatus = async (status: number) => {
  let ids: any[] = []
  if (multipleSelection.value.length === 0) {
    return ElMessage.warning('请选择要操作的记录')
  }
  ids = multipleSelection.value.map((obj) => obj.id)
  ElMessageBox.confirm(`确定要修改状态吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const updateFun: any = []
      ids.forEach(async (id: number) => {
        updateFun.push(api.Asset.update({ id, assetStatus: status }))
      })
      const res = await Promise.all(updateFun)
      const successCount = res.filter((item) => item.code === 200).length
      const errotCount = res.length - successCount
      if (successCount > 0) {
        ElMessage({
          message: `${successCount} 条记录修改成功！`,
          grouping: true,
          type: 'success',
        })
      }
      if (errotCount > 0) {
        ElMessage({
          message: `${errotCount} 条记录修改失败！`,
          grouping: true,
          type: 'error',
        })
      }
      await handlerDialogSubmited()
    })
    .catch(() => {})
}
const handleClickBtnAdd = async () => {
  if (dialogAssetStatisticsRef.value) {
    dialogAssetStatisticsRef.value.openDialog({})
  }
}

const handlerDialogSubmited = async () => {
  await getAssetList()
}
</script>
